<template>
  <!-- 面包屑导航 -->
  <div className="break">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item style="font-size: 22px;padding: 15px 0 0 15px"><b>地址管理</b></el-breadcrumb-item>
    </el-breadcrumb>
  </div>
  <!-- 数据表格 -->
  <!-- 地址卡片列表 -->
  <div style="display: flex; flex-wrap: wrap; margin:20px">
    <el-card
        v-for="address in blogInfo"
        :key="address.id"
        style="width: 30%; margin: 10px;"
    >
      <div>
        <span>姓名: {{ address.name }}</span>
        <br>
        <span>电话号: {{ address.phone }}</span>
        <br>
        <span>地址: {{ address.address }}</span>
      </div>
      <div style="display: flex; justify-content: space-between; align-items: center;">
        <el-radio
            v-model="defaultAddressId"
            :label="address.id"
            @change="setAsDefaultAddress(address.id)"
        >设为默认</el-radio>
        <el-button type="primary" @click="handleEditAddress(address)">编辑</el-button>
      </div>
    </el-card>
  </div>

  <!-- 新增收货地址按钮，使用<router-link>实现导航 -->
  <router-link to="/home/canteen/addressdetail" tag="el-button" type="primary">
    新增收货地址
  </router-link>

  <!-- 编辑地址对话框 -->
  <el-dialog v-model="editDialogVisible" title="编辑地址">
    <el-form :model="editAddressForm" :rules="rules" ref="editForm">
      <el-form-item label="姓名" prop="name">
        <el-input v-model="editAddressForm.name" />
      </el-form-item>
      <el-form-item label="电话号" prop="phone">
        <el-input
            v-model="editAddressForm.phone"
            maxlength="11"
            minlength="11"
            placeholder="请输入11位电话号码"
            show-word-limit
        ></el-input>
      </el-form-item>
      <el-form-item label="地址" prop="address">
        <el-select v-model="editAddressForm.address">
          <el-option label="1公寓" value="1公寓"></el-option>
          <el-option label="2公寓" value="2公寓"></el-option>
          <el-option label="6公寓" value="6公寓"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="saveAddress">保存地址</el-button>
        <el-button type="danger" @click="deleteAddress">删除地址</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script setup>
import { onMounted, reactive, ref } from "vue";
import request from "@/utils/canteen";
import { ElMessage, ElDialog, ElForm, ElFormItem, ElInput, ElButton, ElRadio } from "element-plus";

// 从sessionStorage获取当前登录学生的loginUser对象
const loginUser = JSON.parse(sessionStorage.getItem('loginUser'));

// 从loginUser对象中获取学生的id
const stuId = ref(loginUser? loginUser.id : null);

const blogInfo = ref([]);

const editDialogVisible = ref(false);
const editAddressForm = reactive({
  id: null,
  name: '',
  phone: '',
  address: ''
});

// 添加验证规则
const rules = reactive({
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '必须填写手机号', trigger: 'blur' },
    {
      pattern: /^(?:13[3-9]|14[5-9]|15[0-3]|15[5-9]|16[6]|17[3]|18[2-9]|19[3-9])[0-9]{8}$/,
      message: '格式不正确，请输入有效的手机号',
      trigger: 'blur'
    }
  ],
  address: [
    { required: true, message: '请输入地址', trigger: 'blur' },
    { min: 5, message: '长度至少为 5 个字符', trigger: 'blur' }
  ]
});

onMounted(() => {
  getAddress();
});

// 表格显示内容
const getAddress = () => {
  const params = {
    stuid: stuId.value,
  };

  request({
    url: '/address/getAll',
    method: 'get',
    params,
  }).then((response) => {
    console.log(response);
    if (response.data.errorCode === 200) {
      blogInfo.value = response.data.data;
    } else {
      ElMessage.error('获取地址失败');
    }
  }).catch((error) => {
    console.error('请求错误:', error);
    ElMessage.error('请求地址列表时发生错误');
  });
};

// 处理编辑地址的函数
const handleEditAddress = (address) => {
  editAddressForm.id = address.id;
  editAddressForm.name = address.name;
  editAddressForm.phone = address.phone;
  editAddressForm.address = address.address;
  editDialogVisible.value = true;
};

const setAsDefaultAddress = (newDefaultId) => {
  request({
    url: `/address/setDefaultAddress/${newDefaultId}`,
    method: 'post',
  }).then((response) => {
    if (response.status === 200) {
      ElMessage.success('默认地址设置成功');
      getAddress(); // 重新获取地址列表以更新默认地址状态
    } else {
      ElMessage.error('设置默认地址失败');
    }
  }).catch((error) => {
    console.error('设置默认地址时发生错误:', error);
    ElMessage.error('设置默认地址时发生错误');
  });
};

// 保存编辑后的地址
const saveAddress = () => {
  const editForm = ref(null);
  editForm.value.validate((valid) => {
    if (valid) {
      request({
        url: '/address/updateAll',
        method: 'put',
        data: editAddressForm
      }).then((response) => {
        if (response.status === 200) {
          ElMessage.success('地址保存成功');
          editDialogVisible.value = false;
          getAddress();
        } else {
          ElMessage.error('地址保存失败');
        }
      }).catch((error) => {
        console.error('保存地址时发生错误:', error);
        ElMessage.error('保存地址时发生错误');
      });
    } else {
      console.log('表单验证失败：', editForm.value);
      return false;
    }
  });
};

// 删除地址
const deleteAddress = () => {
  request({
    url: `/address/del/${editAddressForm.id}`,
    method: 'delete',
  }).then((response) => {
    if (response.status === 200) {
      ElMessage.success('地址删除成功');
      editDialogVisible.value = false;
      getAddress();
    } else {
      ElMessage.error('地址删除失败');
    }
  }).catch((error) => {
    console.error('删除地址时发生错误:', error);
    ElMessage.error('删除地址时发生错误');
  });
};
</script>
